package com.beemans.corekit.integration.polling;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.ExistingWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.beemans.corekit.integration.toolkit.AppUtils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class LocalPollingWorker extends Worker {
    private static final String TAG = LocalPollingWorker.class.getSimpleName();
    private static final long CHECK_INTERVAL = 15 * 1000;

    // 上一次检索时间戳
    private static final AtomicLong lastCheckInterval = new AtomicLong(0);

    @Nullable
    private static PeriodicWorkRequest mRequest;

    public LocalPollingWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        // 系统为了减少电量消耗，可能会将触发时间临近的几个任务放在一起执行
        final long now = System.currentTimeMillis();
        final long last = lastCheckInterval.get();
        if (Math.abs(now - last) < CHECK_INTERVAL) {
            return Result.success();
        }

        lastCheckInterval.set(now);

        LocalPolling.getInstance().checkPolling(false);
        scheduleSingleExecutionTask();
        return Result.success();
    }

    public static void start() {
        if (mRequest == null) {
            mRequest = new PeriodicWorkRequest.Builder(LocalPollingWorker.class, 15, TimeUnit.MINUTES)
                    // 延迟1分钟执行
                    .setInitialDelay(1, TimeUnit.MINUTES)
                    .build();
        }

        final String uniqueWorkName = TAG + ExistingPeriodicWorkPolicy.KEEP.name();
        WorkManager.getInstance(AppUtils.getApp())
                // 避免任务被重复多次加入队列
                .enqueueUniquePeriodicWork(uniqueWorkName, ExistingPeriodicWorkPolicy.KEEP, mRequest);

        scheduleSingleExecutionTask();
    }

    private static void scheduleSingleExecutionTask() {
        // 添加一个立即执行的一次性任务
        final OneTimeWorkRequest oneTimeRequest = new OneTimeWorkRequest.Builder(LocalPollingWorker.class)
                .setInitialDelay(CHECK_INTERVAL, TimeUnit.MILLISECONDS) // 稍作延迟避免冲突
                .build();

        final String uniqueWorkName = TAG + ExistingWorkPolicy.REPLACE.name();
        WorkManager.getInstance(AppUtils.getApp())
                .enqueueUniqueWork(uniqueWorkName, ExistingWorkPolicy.REPLACE, oneTimeRequest);
    }
}